package com.eportal.action.background;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.domain.AppStore;
import com.eportal.domain.FixApply;
import com.eportal.domain.FixFixer;
import com.eportal.domain.Sysmenu;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TOpenLog;
import com.eportal.domain.TUsers;
import com.eportal.service.AppStoreService;
import com.eportal.service.FixService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TUsersService;
import com.eportal.service.impl.TCommunityServiceImpl;
import com.eportal.util.CityUtil;
import com.eportal.util.Config;
import com.eportal.util.DateUtils;
import com.eportal.util.HomePageConfig;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 报修管理
 * @author chencheng
 *
 */
public class FixAction extends BaseAction implements ModelDriven<FixFixer> {
	
	private static Logger log = Logger.getLogger(FixAction.class);
	
    /**
	 * @author chencheng
	 */
	private static final long serialVersionUID = 1L;

    private Map<String, Object> result = new HashMap<String, Object>();
    
    private static String FIXURL="/admin/fix_listView.action";
    @Autowired
    FixService fixService;
    @Autowired
    AppStoreService appStoreService;
    @Autowired
    TUsersService tUsersService;
    @Autowired
    TCommunityService tCommunityService;
    /**
     * 报修管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	String homePageConfig = HomePageConfig.BAOXIU;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
        return SUCCESS;
    }
    /**
     * 维修工管理
     */
    public String fixerList() {
    	String homePageConfig = HomePageConfig.BAOXIU;
    	String[] str = homePageConfig.split(",");
    	getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	return SUCCESS;
    }
    
    /**
     * 维修工完成维修管理
     */
    public String fixerFixListView() {
    	String homePageConfig = HomePageConfig.BAOXIU;
    	String[] str = homePageConfig.split(",");
    	getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	
    	getRequest().setAttribute("fixerid", getRequest().getParameter("fixerid"));
    	
    	boolean ifdelete = false;
    	List<Sysmenu> resources = null;
    	Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
        map = (Map<String, Object>) map.get("buttons");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            if (key.contains(FIXURL)) {
                resources = (List<Sysmenu>) entry.getValue();
            }
        }
        if (resources != null && resources.size() > 0) {
        	for (Sysmenu menu : resources) {
        		if("报修删除".equals(menu.getmName())){
        			ifdelete = true;
        			break;
        		}
        	}
        }
        
        getRequest().setAttribute("ifdelete", ifdelete);
    	return SUCCESS;
    }
    /**
     * 维修工准备维修管理
     */
    public String fixerNoFixListView() {
    	String homePageConfig = HomePageConfig.BAOXIU;
    	String[] str = homePageConfig.split(",");
    	getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	
    	getRequest().setAttribute("fixerid", getRequest().getParameter("fixerid"));
    	
    	boolean ifdelete = false;
    	List<Sysmenu> resources = null;
    	Map<String, Object> map = (Map<String, Object>) getSession().getAttribute("auths");
    	map = (Map<String, Object>) map.get("buttons");
    	for (Map.Entry<String, Object> entry : map.entrySet()) {
    		String key = entry.getKey();
    		if (key.contains(FIXURL)) {
    			resources = (List<Sysmenu>) entry.getValue();
    		}
    	}
    	if (resources != null && resources.size() > 0) {
    		for (Sysmenu menu : resources) {
    			if("报修删除".equals(menu.getmName())){
    				ifdelete = true;
    				break;
    			}
    		}
    	}
    	
    	getRequest().setAttribute("ifdelete", ifdelete);
    	return SUCCESS;
    }
    
    /**
     * 报修管理列表
     */
    public void page() throws Exception {
        JqGridPager jqGridPager = new JqGridPager();
    	String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String areaCode = getRequest().getParameter("areaCode");
    	String userName = getRequest().getParameter("userName");
    	String userTel = getRequest().getParameter("userTel");
    	String replytype = getRequest().getParameter("replytype");
    	String status = getRequest().getParameter("status");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.admin_del=1 ");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (StringUtils.isNotBlank(agtCode)) {
                where.append(" and t.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
        	if (StringUtils.isNotBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
        	if (userRole == 21) {
				where.append(" and a.sysoptId=");
				where.append(user.getSid());
			}
		}else	if (userRole == 3 || userRole == 4) {
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			if (StringUtils.isNotBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    		if (StringUtils.isNotBlank(userName)) {
        		where.append(" and tu.auname like'%");
        		where.append(userName);
        		where.append("%'");
        	}
    		if (StringUtils.isNotBlank(userTel)) {
        		where.append(" and t.apply_tel like'%");
        		where.append(userTel);
        		where.append("%'");
        	}
    	}
    	
    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(c.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{									
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	
    	if (StringUtils.isBlank(replytype)) {
    		if(StringUtils.isNotBlank(status)){//修理状态
    			where.append(" and t.status=");
        		where.append(status);
    		}
    	}else if("0".equals(replytype)){//待回复，修理状态为已申请，或者撤销且未指定修理工的
    		if(StringUtils.isBlank(status)){//修理状态
    			where.append(" and (t.status=1 or (t.status=2 and t.fixer_id is null))");
    		}else{
    			switch (status) {
				case "1":
					where.append(" and t.status=1 ");
					break;
				case "2":
					where.append(" and t.status=2 and t.fixer_id is null");
					break;
				case "3":
				case "4":
					return;
				}
    		}
    	}else{//已回复，状态为撤销且指定修理工的，维修中，已完成
    		if(StringUtils.isBlank(status)){//修理状态
    			where.append(" and (t.status=3 or t.status=4 or (t.status=2 and t.fixer_id is not null))");
    		}else{
    			switch (status) {
    			case "1":
    				return;
    			case "2":
    				where.append(" and t.status=2 and t.fixer_id is not null");
    				break;
    			case "3":
    			case "4":
    				where.append(" and t.status=");
    				where.append(status);
    				break;
    			}
    		}
    	}
    	
    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<Map<String, Object>> fixlist = fixService.list(jqGridPager);
        jqGridQueryMap(TOpenLog.class, getRequest(), fixlist, getResponse(), jqGridPager);
    }
    
    /**
     * 报修已完成或未完成管理列表
     */
    public void fixerFixListPage() throws Exception {
    	JqGridPager jqGridPager = new JqGridPager();
    	String userName = getRequest().getParameter("userName");
    	String userTel = getRequest().getParameter("userTel");
    	String status = getRequest().getParameter("status");
    	String fixerid = getRequest().getParameter("fixerid");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.admin_del=1 ");
    	
    	if (userRole != 5 && userRole != 6) {
    		return;
    	}
    	if(StringUtils.isNotBlank(status)){//修理状态
    		where.append(" and t.status=");
    		where.append(status);
    	}else{
    		where.append(" and (t.status =3 or t.status=4) ");
    	}
    	
    	if (StringUtils.isNotBlank(fixerid)) {
    		where.append(" and f.sid =");
    		where.append(fixerid);
    	}
    	if (StringUtils.isNotBlank(userName)) {
    		where.append(" and f.cname like'%");
    		where.append(userName);
    		where.append("%'");
    	}
		if (StringUtils.isNotBlank(userTel)) {
    		where.append(" and f.tel like'%");
    		where.append(userTel);
    		where.append("%'");
    	}
    	
    	jqGridPager.setWhere(where.toString());
    	setPage(getRequest(), jqGridPager);
    	List<Map<String, Object>> fixlist = fixService.fixerFixList(jqGridPager);
    	jqGridQueryMap(TOpenLog.class, getRequest(), fixlist, getResponse(), jqGridPager);
    }
	
    /**
     * 报修人员管理列表
     */
    public void fixerPage() throws Exception {
    	JqGridPager jqGridPager = new JqGridPager();
    	String userName = getRequest().getParameter("userName");
    	String userTel = getRequest().getParameter("userTel");
    	
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.admindel=1 ");
    	if (userRole != 5 && userRole != 6) {
    		return;
    	}
    	
    	where.append(" and t.communityId ='");
    	where.append(user.getCommunityId());
    	where.append("'");
    	if (StringUtils.isNotBlank(userName)) {
    		where.append(" and t.cname like'%");
    		where.append(userName);
    		where.append("%'");
    	}
    	if (StringUtils.isNotBlank(userTel)) {
    		where.append(" and t.tel like'%");
    		where.append(userTel);
    		where.append("%'");
    	}
    	
    	jqGridPager.setWhere(where.toString());
    	setPage(getRequest(), jqGridPager);
    	List<Map<String, Object>> fixer = fixService.fixerList(jqGridPager);
    	jqGridQueryMap(TOpenLog.class, getRequest(), fixer, getResponse(), jqGridPager);
    }
    
    
    /**
     * 维修工新增
     */
    public String fixerAddView() {
        return SUCCESS;
    }
    /**
     * 维修工修改
     */
    public String fixerEditView() {
    	FixFixer fixFixer = fixService.getFixFixer(getModel().getSid());
    	getRequest().setAttribute("fixFixer", fixFixer);
    	return SUCCESS;
    }
    
    /**
     * 维修工保存
     */
    public void fixerAdd(){
    	try{
    		FixFixer fixFixer = getModel();
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	String userid =  getUserid(fixFixer.getTel(),user.getCommunityId());
        	if(userid!=null){
        		fixFixer.setAppUserid(userid);
            	result = fixService.addMethod(fixFixer);
        	}else{
    		  result.put("code", 0);
              result.put("msg", "未找到该手机号对应的app用户，请重新确认");
        	}
    	}catch(Exception e){
    		result.put("code", 0);
            result.put("msg", "操作失败");
    		log.error(this, e);
    	}
        responseBody(result);
    }
    
    /**
     * 维修工更新保存
     */
    public void fixerUpdate(){
    	try{
    		FixFixer fixFixer = getModel();
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	String userid =  getUserid(fixFixer.getTel(),user.getCommunityId());
        	if(userid!=null){
        		fixFixer.setAppUserid(userid);
        		result = fixService.updateMethod(fixFixer);
        	}else{
    		  result.put("code", 0);
              result.put("msg", "未找到该手机号对应的app用户，请重新确认");
        	}
    	}catch(Exception e){
    		result.put("code", 0);
            result.put("msg", "操作失败");
    		log.error(this, e);
    	}
        responseBody(result);
    }
    
    /**
     * 通过手机号和社区id获取对应的app 用户userid
     * @param tel
     * @param communityid
     * @return
     */
    public String  getUserid(String tel,String communityid){
    	TCommunity comm = tCommunityService.get(Long.valueOf(communityid));
    	String userid = null;
    	if(comm!=null){
    		TUsers users = tUsersService.getByWhere(" appid='"+comm.getAppId()+"' and tel='"+tel+"'");
    		if(users!=null){
    			userid = users.getUserId();	
    		}
    	}
    	return userid;
    }
    
    /**
     * 维修工删除
     */
    public void fixerDelete(){
    	String ids = getRequest().getParameter("ids");
    	result = fixService.deleteMethod(ids);
        responseBody(result);
    }
    
    /**
     * 报修删除
     */
    public void delete(){
    	String ids = getRequest().getParameter("ids");
    	result = fixService.deleteFixMethod(ids);
    	responseBody(result);
    }
    
    /**
     * 回复弹窗
     */
    public String replyView() {
    	String sid = getRequest().getParameter("sid");
    	getRequest().setAttribute("sid", sid);
        return SUCCESS;
    }
    
    /**
     * 回复详情
     */
    public String replyDetailView() {
    	String sid = getRequest().getParameter("sid");
    	StringBuilder sql = new StringBuilder("select f.cname,f.type,f.tel,to_char(t.fix_start_time,'yyyy-mm-dd') as startTime, to_char(t.fix_end_time,'yyyy-mm-dd') as endtime,to_char(t.replyTime,'yyyy-mm-dd HH24:mi:ss') as replyTime from FIX_APPLY t left join fix_fixer f on t.fixer_id=f.sid where t.sid=");
		sql.append(sid);
    	Map<String, String> replyDetailMap = fixService.getDetailBySql(sql.toString());
        getRequest().setAttribute("map", replyDetailMap);
        return SUCCESS;
    }
    
    /**
     * 回复
     */
    public void reply(){
    	
    	try{
    		String sid  = getRequest().getParameter("sid");
        	String fixerId  = getRequest().getParameter("fixerId");
        	String fixStartTime  = getRequest().getParameter("fixStartTime");
        	String fixEndTime  = getRequest().getParameter("fixEndTime");
        	if (StringUtils.isBlank(sid)) {
        		 result.put("code", 0);
                 result.put("msg", "未找到该申请数据，请刷新重试");
                 responseBody(result);
                 return;
    		}
        	if (StringUtils.isBlank(fixerId)) {
        		 result.put("code", 0);
                 result.put("msg", "未找到维修工，维修工必选");
                 responseBody(result);
                 return;
        	}
        	if (StringUtils.isBlank(fixStartTime)) {
        		 result.put("code", 0);
                 result.put("msg", "最早上门时间必填");
                 responseBody(result);
                 return;
        	}
        	if (StringUtils.isBlank(fixEndTime)) {
        		 result.put("code", 0);
                 result.put("msg", "最晚上门时间必填");
                 responseBody(result);
                 return;
        	}

        	FixFixer fixer = fixService.getFixFixer(Long.valueOf(fixerId));
        	if(fixer.getAppUserid()==null){
        		String userid =  getUserid(fixer.getTel(),fixer.getCommunityId());
            	if(userid!=null){
            		fixFixer.setAppUserid(userid);
            		result = fixService.updateMethod(fixer);
            	}else{
	        		  result.put("code", 0);
	                  result.put("msg", "该维修师傅的手机号未找到对应的app用户，请重新确认");
	                  responseBody(result);
	                  return;
            	}
        	}
        	result = fixService.replyMethod(sid,fixerId,fixStartTime,fixEndTime);
        	
        	try {
        		if("1".equals(result.get("code").toString())){
        			MdOpenBaseJson json = MdOpenApi.sendMsg(fixer.getAppUserid(),null,"user","fix_1");	
        		}else{
        			log.info("code="+result.get("code").toString());
        		}
    		} catch (Exception e) {
    			 log.error(this,e);
    		}
        	
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	
    	
        responseBody(result);
    }
    
    /**
     * 所有维修人员列表
     */
    public void fixerAll() throws Exception {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	StringBuilder where = new StringBuilder("from FixFixer  where ");
		where.append(" communityId='");
		where.append(user.getCommunityId());
		where.append("'");
    	List<FixFixer> fixFixers = fixService.listFixerAll(where.toString());
        responseBody(fixFixers);
    }
    
    /**
     * 报修详情
     */
    public String applyDetailView() {
    	String sid = getRequest().getParameter("sid");
    	StringBuilder sql = new StringBuilder("select t.intro,to_char(t.apply_start_time,'yyyy-mm-dd') as starttime,to_char(t.apply_end_time,'yyyy-mm-dd') as endtime,t.pic  from FIX_APPLY t where t.sid=");
		sql.append(sid);
		String url = Config.MD_OPEN_TSHELVES_URL;
		getRequest().setAttribute("url",url);
    	Map<String, String> replyDetailMap = fixService.getDetailBySql(sql.toString());
        getRequest().setAttribute("map", replyDetailMap);
        FixApply apply = fixService.getFixApply(Long.valueOf(sid));
        List datalist = new ArrayList(); 
		if(apply.getSid()!=null){
			Map map = new HashMap();
			map.put("lc1", "待处理");
			map.put("lc2", "已提交报修需求，等待物业处理");
			map.put("date", DateUtils.formatDatetime(apply.getcTime(), "yyyy-MM-dd"));
			map.put("time", DateUtils.formatDatetime(apply.getcTime(), "HH:mm"));
			datalist.add(map);
		}
		
		if(apply.getReplyTime()!=null){
			Map map = new HashMap();
			map.put("lc1", "正在处理");
			map.put("lc2", "物业已确认，即将上门维修");
			map.put("date", DateUtils.formatDatetime(apply.getReplyTime(), "yyyy-MM-dd"));
			map.put("time", DateUtils.formatDatetime(apply.getReplyTime(), "HH:mm"));
			datalist.add(map);
		}

		if(apply.getFinishTime()!=null&&"4".equals(apply.getStatus())){
			Map map = new HashMap();
			map.put("lc1", "完成维修");
			map.put("lc2", "维修师傅已上门，完成维修");
			map.put("date", DateUtils.formatDatetime(apply.getFinishTime(), "yyyy-MM-dd"));
			map.put("time", DateUtils.formatDatetime(apply.getFinishTime(), "HH:mm"));
			map.put("lc_finish", "1");
			datalist.add(map);
		}
		
		if(apply.getCancelTime()!=null&&"2".equals(apply.getStatus())){
			Map map = new HashMap();
			map.put("lc1", "已撤销");
			map.put("lc2", "已撤销报修申请");
			map.put("date", DateUtils.formatDatetime(apply.getCancelTime(), "yyyy-MM-dd"));
			map.put("time", DateUtils.formatDatetime(apply.getCancelTime(), "HH:mm"));
			datalist.add(map);
		}
		getRequest().setAttribute("datalist", datalist);
		getRequest().setAttribute("apply_status", apply.getStatus());
		
        return SUCCESS;
    }
    

    private FixFixer fixFixer = new FixFixer();

    @Override
    public FixFixer getModel() {
        return fixFixer;
    }
}
